/**
 * 
 */
package com.scaffold.commons.config;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

/**
 * @author wangjg
 *
 */
public class ZooKeeperConfig extends AbstractConfig implements Watcher {
	private Map<String,String> configMap = new HashMap<String,String>();
	private Charset charset = null;
	private String rootPath;
	private String connectString;
	
	private ZooKeeper zk = null;
	
	public void init() throws Exception{
		if(this.zk==null){
			this.zk = new ZooKeeper(connectString, 60000, this);
		}
	}
	
	public String getString(String key) {
		String str = configMap.get(key);
		if(str==null){
			str = this.loadValue(key);
		}
		return str;
	}
	
	private String loadValue(String key){
		byte[] buf = this.getData(key);
		String str = new String(buf, charset);
		this.configMap.put(key, str);
		return str;
	}
	
	private byte[] getData(String key){
		String path = rootPath+'/'+key;
		try {
			return zk.getData(path, true, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void process(WatchedEvent event) {
		String path = event.getPath();
		if(path!=null && path.length() > this.rootPath.length()){
			String key = path.substring(this.rootPath.length()+1);
			this.loadValue(key);
		}
	}
	
	public void setRootPath(String rootPath) {
		this.rootPath = rootPath;
	}

	public void setCharset(String charsetName) {
		this.charset = Charset.forName(charsetName);
	}
	
	public static void main(String args[]) throws Exception{
		ZooKeeperConfig zkconf = new ZooKeeperConfig();
		zkconf.setRootPath("/app/gptbs");
		zkconf.connectString = "localhost:2181";
		zkconf.setCharset("utf-8");
		zkconf.init();
		zkconf.getString("aaa");
		
		Thread.sleep(1000*50);
	}

	class MyWatcher implements Watcher{
		public void process(WatchedEvent event) {
			try {
				zk.exists(event.getPath(), this);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
